package ru.kest.babymonitor;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.*;
import android.widget.Button;
import android.widget.Toast;
import ru.kest.babymonitor.gif.GifDecoderView;
import ru.kest.babymonitor.menu.MenuPanel;
import ru.kest.babymonitor.mjpeg.MjpegView;
import ru.kest.babymonitor.mjpeg.OnSwipeTouchListener;
import ru.kest.babymonitor.service.AudioService;
import ru.kest.babymonitor.service.audio.AlarmPlayer;

public class StartActivity extends Activity implements View.OnClickListener {

    private static String TAG = "IPCamBabyMonitor";

    public static boolean running = false;

    private MjpegView mjpegView;
    private MenuPanel menuPanel = null;

    private Settings settings = Settings.getInstance();

    private final static int TIMER_TIME = 1000;

    Handler handler = new Handler();
    Runnable timer = new Runnable() {

        @Override
        public void run() {
            String message = Messenger.getInstance().get();
            if (message != null) {
                if (message.equals(Messenger.RESUME_VIDEO)) {
                    mjpegView = (MjpegView) findViewById(R.id.mjpegView);
                    if (!mjpegView.isRunning()) {
                        startVideo();
                    }
                } else if (message.equals(Messenger.REFRESH_MENU_PANEL)) {
                }
            }

            View soundButton = menuPanel.getMenuView().findViewById(R.id.soundButton);
            if (soundButton != null) {
                boolean buttonShouldBeOn = settings.isAudioOn() || settings.isAudioOnAlarmOn();
                if (soundButton.isSelected() && !buttonShouldBeOn) {
                    soundButton.setSelected(false);
                    Log.d(TAG, "Switch OFF sound button");
                } else if (!soundButton.isSelected() && buttonShouldBeOn) {
                    soundButton.setSelected(true);
                    Log.d(TAG, "Switch ON sound button");
                }
            }

            handler.postDelayed(this, TIMER_TIME);
        }
    };

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        settings.loadSettings(this);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);

        setContentView(R.layout.main);

        mjpegView = (MjpegView) findViewById(R.id.mjpegView);
        mjpegView.setOnTouchListener(new OnSwipeTouchListener(this) {
            public void onTouchDown() {
                doMenu();
            }

            public void onSwipeTop() {
                CamMovement.moveUp();
            }

            public void onSwipeRight() {
                CamMovement.moveRight();
            }

            public void onSwipeLeft() {
                CamMovement.moveLeft();
            }

            public void onSwipeBottom() {
                CamMovement.moveDown();
            }
        });

        Button reloadButton = (Button) findViewById(R.id.reloadButton);
        reloadButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startVideo();
            }
        });

        menuPanel = new MenuPanel(this, this, getLayoutInflater());

        AlarmPlayer.createAlarmPlayer(getBaseContext());
        handler.postDelayed(timer, TIMER_TIME);
    }

    @Override
    protected void onStart() {
        super.onStart();

        settings.loadSettings(this);

        startVideo();

        if (settings.isAudioServiceShouldWork()) {
            startAudioService();
        }
        running = true;
        Log.w(TAG, "onStart(): StartActivity started!");
    }

    @Override
    protected void onStop() {
        super.onStop();
        running = false;
        mjpegView.stopPlayback();
        settings.saveSettings(this);
        Log.w(TAG, "onStop(): StartActivity stopped.");
    }

    private void startVideo() {
        GifDecoderView gifView = (GifDecoderView) findViewById(R.id.loadingGifView);
        gifView.loadGif(R.drawable.loader);
        gifView.startRendering();
        gifView.setVisibility(View.VISIBLE);
        View v = findViewById(R.id.loadingTextView);
        v.setVisibility(View.VISIBLE);
        v = findViewById(R.id.reloadButton);
        v.setVisibility(View.INVISIBLE);

        mjpegView.startPlayback();
    }

    private void startAudioService() {
        Intent intent = new Intent(this, AudioService.class);
        startService(intent);
    }

    /**
     * Toggle our menu on user pressing the menu key.
     */
    private void doMenu() {
        if (menuPanel.isShowing()) {
            menuPanel.hide();
        } else {
            //Note it doesn't matter what widget you send the menu as long as it gets view.
            menuPanel.show(findViewById(R.id.mjpegView));
        }
    }

    /**
     * Snarf the menu key.
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            doMenu();
            return true; //always eat it!
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.soundButton: // Sound on / off
                v.setSelected(!v.isSelected());
                if (v.isSelected()) {
                    settings.setAudioOn(true);
                    startAudioService();
                } else {
                    settings.setAudioOnAlarmOn(false);
                    settings.setAudioOn(false);
                    AlarmPlayer.getInstance().stopAlarmSound();
                }
                break;
            case R.id.alarmButton: // Alarm on / off
                v.setSelected(!v.isSelected());
                if (v.isSelected()) {
                    settings.setAlarmOn(true);
                    startAudioService();
                } else {
                    settings.setAlarmOn(false);
                }
                break;
            case R.id.settingsButton:
                Intent intent = new Intent(this, SettingsActivity.class);
                startActivity(intent);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        menuPanel.hide();
        super.onDestroy();
        Log.w(TAG, "onDestroy()!");
    }
}
